using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ContosoUniversity.Data;
using ContosoUniversity.Models;
using ContosoUniversity.Models.SchoolViewModels;

namespace ContosoUniversity.Pages.Instructors
{
    public class IndexModel : PageModel
    {
        private readonly ContosoUniversity.Data.SchoolContext _context;

        public IndexModel(ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }

        //public IList<Instructor> Instructor { get;set; }

        //public async Task OnGetAsync()
        //{
        //    Instructor = await _context.Instructors.ToListAsync();
        //}

        public InstructorIndexData Instructor { get; set; }

        public int InstructorID { get; set; }

        public int CourseID { get; set; }

        public async Task OnGetAsync(int? id, int? courseID)
        {
            Instructor = new InstructorIndexData();
            Instructor.Instructors = await _context.Instructors
                .Include(i => i.OfficeAssignment)
                .Include(i => i.CourseAssignments)
                    .ThenInclude(i => i.Course)
                        .ThenInclude(i => i.Department)
                // eager loading
                //    .Include(i=>i.CourseAssignments)
                //        .ThenInclude(i=>i.Course)
                //            .ThenInclude(i=>i.Enrollments)
                //                .ThenInclude(i=>i.Student)
                //.AsNoTracking()
                .OrderBy(i => i.LastName)
                .ToListAsync();

            if (id.HasValue)
            {
                InstructorID = id.Value;
                var instructor = Instructor.Instructors.Single(i => i.ID == id.Value);
                Instructor.Courses = instructor.CourseAssignments.Select(s => s.Course);
            }

            if (courseID.HasValue)
            {
                CourseID = courseID.Value;
                var selectedCourse = Instructor.Courses.Single(i => i.CourseID == courseID.Value);
                await _context.Entry(selectedCourse).Collection(x => x.Enrollments).LoadAsync();
                foreach (var item in selectedCourse.Enrollments)
                {
                    await _context.Entry(item).Reference(s => s.Student).LoadAsync();
                }

                Instructor.Enrollments = selectedCourse.Enrollments;

                // eager loading
                //Instructor.Enrollments = Instructor.Courses
                //    .Where(x => x.CourseID == courseID.Value)
                //    .Single().Enrollments;
            }
        }
    }
}
